package cn.com.dashihui.api.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;

import cn.com.dashihui.api.base.BaseController;


/**
 * 拦截异步请求，然后作相应处理
 */
public abstract class AjaxInterceptor implements Interceptor{

	public void intercept(Invocation inv) {
		BaseController c = (BaseController)inv.getController();
		
		//当请求为异步AJAX请求时，比传统请求多了一个头信息X-Requested-With，可通过判断该参数是否存在以确定是否是异步请求
		String xRequestedWith = c.getRequest().getHeader("X-Requested-With");
		//设置响应头  解决异步跨域问题
				c.getResponse().setHeader("Access-Control-Allow-Origin", "*");
				c.getResponse().setHeader("Access-Control-Allow-Credentials", "true");
				c.getResponse().setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With");
				c.getResponse().setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");

		if(!StrKit.isBlank(xRequestedWith)&&xRequestedWith.equals("XMLHttpRequest")){
			onAjax(inv);
		}else{
			onAjaxNope(inv);
		}
	}

	/**
	 * 当是异步请求时的处理
	 */
	public abstract void onAjax(Invocation inv);
	
	/**
	 * 当不是异步请求时的处理
	 */
	public abstract void onAjaxNope(Invocation inv);
}
